package com.jijs.guava.base;

import com.google.common.base.Joiner;
import com.google.common.collect.Maps;

import java.util.Map;

/**
 * Google Guava提供了Joiner类专门用来连接String。
 * Created by jjs on 2016/12/31.
 * @author jijs
 */
public class JoinerTest {

    /**
     * 譬如说有个String数组，里面有"a","b","c"，我们可以通过使用StringBuilder来创建String "a,b,c"。
     *
     * Joiner提供了这一类的功能。
     */
    public static void join() {
        Joiner joiner = Joiner.on(";");
        String s = joiner.join(new String[]{"a", "b", "c"});  //a;b;c
        System.out.println(s);
    }

    /**
     * Joiner还提供了appendTo函数，对传入的StringBuilder作处理：
     */
    public static void appendTo() {
        Joiner joiner = Joiner.on(";");
        StringBuilder ab = new StringBuilder("start: ");
        String s = joiner.appendTo(ab, new String[]{"a", "b", "c"}).toString();
        System.out.println(s);  //"start: a;b;c"
    }

    /**
     * MapJoiner类也利用Joiner提供了Map的join功能：
     */
    public static void withKeyValueSeparator() {
        Map<Integer, String> map = Maps.newHashMap();
        map.put(1, "a");
        map.put(2, "b");
        Joiner.MapJoiner joiner = Joiner.on(";").withKeyValueSeparator("->");
        System.out.println(joiner.join(map));   //"1->a;2->b"
    }

    /**
     * 需要注意的是Joiner类是immutable的。换言之，它是线程安全的，你可以把它static final来用没问题。
     * 但是这样的话，正如javadoc所举的例子：
     */
    public static void skipNulls(){
        // Bad! Do not do this!
        String s = Joiner.on(',').skipNulls().join("wrong", null, "wrong");
        System.out.println(s);
    }

    public static void main(String[] args) {
//        join();
//        appendTo();
//        withKeyValueSeparator();
        skipNulls();
    }
}
